
<template>
  <div class="settings-container">
    <app-header></app-header>
    <div class="settings-card">
      <div class="title-container">
        <h2 class="settings-title">完善实名信息</h2>
        <base-button class="update-password-btn" @click="openPasswordRest">修改密码</base-button>
      </div>
      <base-form :model="userForm" :rules="rules" ref="userForm" label-width="120px">
        <base-form-item label="姓名" prop="name">
          <base-input v-model="userForm.name" placeholder="请输入姓名"/>
        </base-form-item>

        <base-form-item label="机构" prop="institution">
          <base-input v-model="userForm.institution" placeholder="请输入所属机构"/>
        </base-form-item>

        <base-form-item label="研究领域">
          <Keywords v-model="userForm.researchFields" text="研究领域"/>

        </base-form-item>

<!--        <base-form-item label="ORCID">-->
<!--          <base-input v-model="userForm.orcid" placeholder="请输入ORCID"></base-input>-->
<!--        </base-form-item>-->

        <base-form-item label="邮箱" prop="email">
          <base-input v-model="userForm.email" placeholder="请输入邮箱"/>
        </base-form-item>

        <base-form-item v-if="emailVerificationStatus" label="邮箱验证码">
          <div class="verification-code">
            <base-input v-model="userForm.verificationCode" placeholder="请输入邮箱验证码"/>
            <base-button type="primary" class="verification-btn" @click="sendVerificationCode" :disabled="cooldown > 0">
              {{ cooldown > 0 ? `${cooldown}秒后重试` : '获取验证码' }}
            </base-button>
          </div>
        </base-form-item>

        <base-form-item label="手机号" prop="mobile" class="form-item">
          <base-input v-model="userForm.mobile" placeholder="请输入手机号"/>
        </base-form-item>

        <base-form-item v-if="mobileVerificationStatus" label="手机验证码">
          <div class="verification-code">
            <base-input v-model="userForm.mobileCode" placeholder="请输入手机验证码"/>
            <base-button type="primary" class="mobile-btn" @click="sendMobileCode(userForm.mobile)" :disabled="mobileCooldown > 0">
              {{ mobileCooldown > 0 ? `${mobileCooldown}秒后重试` : '获取验证码' }}
            </base-button>
          </div>
        </base-form-item>

        <base-form-item class="submit-container">
          <base-button type="primary" class="submit-btn" @click="submitForm">保存修改</base-button>
        </base-form-item>
      </base-form>
    </div>
  </div>
</template>

<script>
import AppHeader from './components/AppHeader.vue';
import {
  UpdateUser,
  SendCodeEmail, SendCodeMobile
} from '@/service/user'
import {Keywords} from '@zkwq/business'
import {getAuthHostName, outLogin, toLogin} from "@/service/login";
import {CACHE_KEY} from "@/constants";
import {BaseUtil} from "@zkwq/business/dist";

export default {
  components:{
    AppHeader,Keywords
  },
  data() {
    return {
      userForm: {
        id: '',
        name: '',
        institution: '',
        researchFields: [],
        researchField:'',
        orcid: '',
        email: '',
        verificationCode: '',
        mobile: '',
        mobileCode: ''
      },
      cooldown: 0,
      mobileCooldown: 0,
      originalUser: {},
    }
  },
  created() {
    this.userForm.id = this.user.id;
    this.userForm.name = this.user.name
    this.userForm.institution = this.user.institution
    this.userForm.researchFields = this.user.researchField?.split(';')
    this.userForm.orcid = this.user.orcid
    this.userForm.email = this.user.email
    this.userForm.mobile = this.user.mobile
    this.originalUser = this.user
  },
  computed: {
    rules() {
      console.log(this.userForm.mobile !== this.originalUser.mobile)
      return {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }],
        institution: [
          { required: true, message: '请输入机构', trigger: 'blur' }
        ],
        researchField: [
          { required: true, message: '请输入研究领域', trigger: 'blur' }
        ],

        email: [
          { required: !!this.originalUser.email, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur'}
        ],
        verificationCode: [
          { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
        ],
        mobile: [
          { required: !!this.originalUser.mobile, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        mobileCode: [
          { required: true, message: '请输入手机验证码', trigger: 'blur' }
        ]
      }
    },
    emailVerificationStatus() {
      const current = this.userForm.email || undefined;
      const original = this.originalUser.email || undefined;
      return current !== original;
    },
    mobileVerificationStatus() {
      const current = this.userForm.mobile || undefined;
      const original = this.originalUser.mobile || undefined;
      return current !== original;
    },
  },
  methods: {
    openPasswordRest() {
      const fullUrl = getAuthHostName() + "/oauth/authorize/password_reset";
      window.open(fullUrl, '_blank');
    },
    // 发送邮箱验证码
    sendVerificationCode() {
      if (this.cooldown > 0) return
      if(!this.validateEmail(this.userForm.email)){
        this.$message.error('请输入正确的邮箱地址')
        return
      }

      // TODO: 调用发送验证码API
      SendCodeEmail(this.userForm.email).then(res => {
        if (res.code === 0) {
          this.$message.success('发送成功')
          this.cooldown = 60
          const timer = setInterval(() => {
            this.cooldown--
            if (this.cooldown <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        } else if (res.msg) {
          this.$message.error(res.msg)
        } else {
          this.$message.error('发送失败,请重试')
        }
      })
    },
    validateEmail(email) {
      if (email === undefined || email == null || email === '') {
        return false
      }
      // 基础邮箱验证正则
      const reg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return reg.test(email);
    },
    sendMobileCode(mobile) {
      if (this.mobileCooldown > 0) return
      if(!this.validatePhoneDetailed(mobile)){
        this.$message.error('请输入正确的手机号')
        return
      }
      SendCodeMobile(mobile).then(res => {
        if (res.code === 0) {
          this.$message.success('发送成功')
          this.mobileCooldown = 60
          const timer = setInterval(() => {
            this.mobileCooldown--
            if (this.mobileCooldown <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        }else if (res.msg) {
          this.$message.error(res.msg)
        } else {
          this.$message.error('发送失败,请重试')
        }
      })
    },
    validatePhoneDetailed(phone) {
      if (phone === undefined || phone == null || phone === '') {
        return false
      }
      const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      return reg.test(phone);
    },
    // 提交表单
    submitForm() {
      if(this.emailVerificationStatus && !this.userForm.verificationCode){
        this.$message.error('请输入邮箱验证码')
        return
      }
      if(this.mobileVerificationStatus && !this.userForm.mobileCode){
        this.$message.error('请输入手机验证码')
        return
      }
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            this.userForm.researchField = this.userForm.researchFields?.join(';')
            const res = await UpdateUser(this.userForm)
            if(res.code !== 0){
              this.$message.error(res.msg)
              return
            }
            this.setUser(res.data)
            this.$message.success('保存成功')
            await this.$router.push({ path: '/' })
            toLogin()
          } catch (error) {
            console.log(error)

            this.$message.error('保存失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>

.form-item {
  position: relative;
}

.form-item :deep(.base-form-item__error) {
  position: absolute;
  left: 78%;  /* 移动到右侧 */
  top: -1px;
  white-space: nowrap; /* 防止换行 */
}

.title-container {
  position: relative;
  margin-bottom: 35px;
  padding-bottom: 20px;
  border-bottom: 2px solid #eef2f7;
}

.update-password-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background: linear-gradient(45deg, #4481eb, #04befe);
  border: none;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
}

.settings-container {
  width: 100%;
  min-height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.settings-card {
  width: 800px;
  margin: 40px auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 35px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.settings-card:hover {
  transform: translateY(-2px);
}

.settings-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
  letter-spacing: 0.5px;
  display: inline-block;
}

.verification-code {
  display: flex;
  gap: 15px;
}

.verification-code .el-input {
  flex: 1;
}

.verification-btn {
  min-width: 120px;
  background: linear-gradient(45deg, #4481eb, #04befe);
  border: none;
  transition: all 0.3s ease;
}

.verification-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 5px 15px rgba(68, 129, 235, 0.2);
}

.submit-container {
  margin-top: 45px;
  text-align: center;
}

.submit-btn {
  min-width: 140px;
  padding: 12px 35px;
  font-size: 16px;
  background: linear-gradient(45deg, #4481eb, #04befe);
  border: none;
  letter-spacing: 1px;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(68, 129, 235, 0.2);
}

/* 输入框样式优化 */
:deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #4481eb;
  box-shadow: 0 0 0 2px rgba(68, 129, 235, 0.1);
}

/* 表单项间距优化 */
:deep(.el-form-item) {
  margin-bottom: 28px;
}

/* 标签文字样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
  font-size: 15px;
}

/* 禁用状态样式 */
:deep(.el-button.is-disabled) {
  background: #a0cfff !important;
  border: none;
  opacity: 0.7;
}
</style>